package com.example.springbootsecurity.security;

import com.example.springbootsecurity.entity.ShiroMenu;
import com.example.springbootsecurity.service.ShiroMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component("rbacService")
public class RbacServiceImpl {

    @Autowired
    private ShiroMenuService menuService;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;
        if (principal instanceof UserDetails) { //首先判断先当前用户是否是我们UserDetails对象。
            UserDetails userDetails = (UserDetails) principal;
            String userName = userDetails.getUsername();
            System.out.println(request.getRequestURI());
            System.out.println(request.getRequestURL());
            System.out.println(request.getQueryString());

            Set<String> urls = new HashSet<>(); // 数据库读取 //读取用户所拥有权限的所有URL
            List<ShiroMenu> menuList = menuService.getMenuByUser(userName);
            if (menuList != null && menuList.size() > 0){
                for(ShiroMenu menu : menuList){
                    urls.add(menu.getMenuPath());
                }
            }
            // 注意这里不能用equal来判断，因为有些URL是有参数的，所以要用AntPathMatcher来比较
            for (String url : urls) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
        }
        return hasPermission;
    }
}
